<template>
  <div
    id="device-tree"
    class="dtree-wrap"
    :class="(!showTabs ? 'deviceTree' : '') || activeName === 'second' ? 'deviceTree': ''"
  >
    <template v-if="showDeviceIndex">
      <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
        <el-tab-pane :label="$t('终端分组')" name="first">
          <div class="ctl-box" v-show="showTabs">
            <bs-add-icon
              class="hover-effect"
              @click.native="addTreeNode"
            ></bs-add-icon>
            <bs-remove-icon
              class="hover-effect"
              @click.native="removeTreeNode"
            ></bs-remove-icon>
            <bs-edit-icon
              class="hover-effect"
              @click.native="editTreeNode"
            ></bs-edit-icon>
            <bs-setting-icon
              class="hover-effect"
              @click.native="settingDevice"
            ></bs-setting-icon>
            <bs-tag-icon
              class="hover-effect"
              @click.native="settingTag"
            ></bs-tag-icon>
            <bs-refresh-icon
              class="hover-effect shuaxin"
              @click.native="refreshNode"
            ></bs-refresh-icon>
          </div>
        </el-tab-pane>
        <el-tab-pane
          :label="$t('终端标签')"
          name="second"
          v-if="showDeviceIndex"
        >
        </el-tab-pane>
      </el-tabs>
    </template>
    <template v-else>
      <div class="main-title">{{ $t('终端分组') }}</div>
      <div class="ctl-box" v-show="showTabs">
        <bs-add-icon
          class="hover-effect"
          @click.native="addTreeNode"
        ></bs-add-icon>
        <bs-remove-icon
          class="hover-effect"
          @click.native="removeTreeNode"
        ></bs-remove-icon>
        <bs-edit-icon
          class="hover-effect"
          @click.native="editTreeNode"
        ></bs-edit-icon>
        <bs-setting-icon
          class="hover-effect"
          @click.native="settingDevice"
        ></bs-setting-icon>
        <bs-refresh-icon
          class="hover-effect shuaxin"
          @click.native="refreshNode"
        ></bs-refresh-icon>
      </div>
    </template>
    <div
      v-if="activeName == 'first'"
      :class="firstAction ? '' : 'no-ctl'"
      class="tree-box"
    >
      <bs-tree
        ref="asyncTree"
        :default-props="defaultProps"
        :default-checked-keys="defaultCheckedKeys"
        :default-expanded-keys="defaultExpandedKeys"
        :show-checkbox="false"
        :draggable="false"
        :filter-visible="false"
        :context-menu-visible="false"
        :context-menu-data="contextMenuData"
        :data="treeData"
        :highlight-current="true"
        @node-click="nodeClick"
      ></bs-tree>
    </div>

    <div style="flex: 1; margin-top: 10px" :class="secondAction ? '' : 'no-ctl'"
      class="tree-box" v-else>
      <device-tag
        v-for="t in treeData"
        :key="t.id"
        :label="t.name"
        :active="treeNodeData.id === t.id"
        @click="nodeClick(t)"
      />
    </div>
    <device-tree-add-dialog @callback="refreshNode"></device-tree-add-dialog>
    <device-tag-dialog @handleOkClick="handleSaveTag"></device-tag-dialog>
  </div>
</template>
<script>
import DeviceTreeAddDialog from '@/views/device/components/DeviceTreeAddDialog'
import DeviceTagDialog from '@/views/device/components/DeviceTagDialog'
import DeviceTag from '@/views/device/components/DeviceTag'
import MediaMonitorApi from '@/api/media'
import $, { map } from 'jquery'

export default {
  data() {
    return {
      treeNodeData: {},
      currentNode: {},
      activeName: 'first',
      defaultProps: {
        id: 'id',
        label: 'name',
        owner: 'owner',
        isLeaf: 'hasChild',
      },
      treeData: [],
      defaultTreeData: {},
      defaultCheckedKeys: [],
      defaultExpandedKeys: [0],
      contextMenuData: [],
    }
  },
  props: {
    showTabs: {
      type: Boolean,
      default: true,
    },
    showDeviceIndex: {
      type: Boolean,
      default: true,
    },
    showMinType: {
      type: String,
      default: '1',
    },
    queryData: {
      default: {},
    },
    haveData: {
      type: Boolean,
      default: false,
    },
    firstAction:{
      type:Boolean,
      default:true,
    },
    secondAction:{
      type:Boolean,
      default:true,
    },
  },
  components: {
    DeviceTag,
    DeviceTagDialog,
    DeviceTreeAddDialog,
  },
  created() {
    this.$eventBus.$on('getTreeNode', this.doClickTree)
  },
  beforeDestroy() {
    this.$eventBus.$off('getTreeNode')
  },
  mounted() {
    this.$nextTick(() => {
      this.loadTreeData()
    })
  },
  methods: {
    //终端分组树
    loadTreeData() {
      this.treeData = [
        {
          id: 0,
          name: '终端分组',
          type: 1,
          children: [],
        },
      ]
      this.treeNodeData = this.treeData[0]
      let params = { type: this.showMinType }
      this.$store.dispatch('device/doLoadTree', params).then((res) => {
        if (res) {
          res.forEach((item) => {
            this.treeData[0].children.push(item)
          })
        }
      })
    },
    // 标签树
    async loadTagTreeData() {
      const res = await MediaMonitorApi.getTag({})
      if (res) {
        this.treeData = res
      }
      console.log(res)
    },

    refreshNode() {
      if (this.activeName == 'first') {
        this.loadTreeData()
      } else {
        this.loadTagTreeData()
      }
    },
    // 点击节点
    nodeClick(data, node, obj) {
      this.treeNodeData = data
      this.currentNode = node
      this.queryData.groupId = data.id == 0 ? -2 : data.id
      this.queryData.page = 1
      this.$eventBus.$emit('doList', this.queryData)
    },
    // 添加节点
    addTreeNode() {
      var arr = Object.keys(this.treeNodeData)
      if (arr.length === 0) {
        this.$alert('提示', '请选择一个终端分组节点')
        return
      }
      const selectTreeID = this.treeNodeData.id
      if (selectTreeID === -1) {
        this.$alert('提示', '默认分组不能添加子节点')
        return
      }
      let editorForm = {}
      editorForm.parentId = selectTreeID == -2 ? 0 : selectTreeID
      this.$eventBus.$emit('showDeviceTreeAddDialog', editorForm)
    },
    // 编辑节点
    editTreeNode() {
      var arr = Object.keys(this.treeNodeData)
      if (arr.length === 0) {
        this.$alert('提示', '请选择一个终端分组节点')
        return
      }
      const selectTreeID = this.treeNodeData.id
      if (selectTreeID === -1 || selectTreeID === 0) {
        this.$alert('提示', '此目录不可操作')
        return
      }

      let editorForm = {}
      editorForm.id = this.treeNodeData.id
      editorForm.name = this.treeNodeData.name
      editorForm.flag=true
      this.$eventBus.$emit('showDeviceTreeAddDialog', editorForm)
    },
    // 删除节点
    removeTreeNode() {
      var arr = Object.keys(this.treeNodeData)
      if (arr.length === 0) {
        this.$alert('提示', '请选择一个终端分组节点')
        return
      }
      const selectTreeID = this.treeNodeData.id
      if (selectTreeID === -1 || selectTreeID === 0) {
        this.$alert('提示', '此目录不可操作')
        return
      }
      this.$confirm('提示', '是否确认删除？').then((bool) => {
        if (bool) {
          if (this.haveData) {
            this.$confirm('提示', '是否确认删除整个分组？').then((bool) => {
              if (bool) {
                const selectTreeID = this.treeNodeData.id
                const params = { id: selectTreeID }
                this.$store
                  .dispatch('device/doDeleteTreeNode', params)
                  .then((res) => {
                    this.currentNode.remove()
                    this.treeNodeData = {}
                    this.$message.success('删除成功')
                  })
              }
            })
          } else {
            const selectTreeID = this.treeNodeData.id
            const params = { id: selectTreeID }
            this.$store
              .dispatch('device/doDeleteTreeNode', params)
              .then((res) => {
                this.currentNode.remove()
                this.treeNodeData = {}
                this.$message.success('删除成功')
              })
          }
        }
      })
    },
    // 设置
    settingDevice() {
      var arr = Object.keys(this.treeNodeData)
      // if(arr.length === 0 || this.treeNodeData.id === 0) {
      //   this.$alert('提示', '请先选择分组')
      //   return
      // }
      if (arr.length === 0) {
        this.$alert('提示', '请选择一个终端分组节点')
        return
      }
      const selectTreeID = this.treeNodeData.id
      if (selectTreeID === 0) {
        this.$alert('提示', '此目录不可操作')
        return
      }
      this.$eventBus.$emit('addDeviceDialogShow', {
        updateGroupId: this.treeNodeData.id,
      })
    },
    async settingTag() {
      var arr = Object.keys(this.treeNodeData)
      if (arr.length === 0) {
        this.$alert('提示', '请选择一个终端分组节点')
        return
      }
      const selectTreeID = this.treeNodeData.id
      if (selectTreeID <= 0) {
        this.$alert('提示', '此目录不可操作')
        return
      }
      let tagids = []
      const res = await this.$store.dispatch('device/doLoadTagListByID', { terminalGroupId: selectTreeID })
      if(res){
        const tagList = res.tagList ? res.tagList : []
        for (var i = 0; i < tagList; i++) {
          if (res.tagList[i].tagIdString) {
            tagids.push(res.tagList[i].tagIdString)
          }
        }
      }
      const ress = await this.$store.dispatch('device/doLoadTagTree', {})
      let treeTagData = []
      if(ress) {
        treeTagData = ress.filter((v) => {
          return v.name !== '内置标签'
        })
      }
      this.$eventBus.$emit('showDeviceTagDialog', treeTagData, tagids)
    },
    // 点击tab页
    doClickTree(treeItem) {
      this.treeNodeData = treeItem
    },

    handleClick(tab, event) {
      delete this.queryData.mac
      delete this.queryData.groupId
      delete this.queryData.tagId
      this.treeNodeData = {}
      this.currentNode = {}
      this.treeData = []
      if (Number(tab.index) === 0) {
        if (this.showTabs) $('#device-tree').removeClass('deviceTree')
        this.loadTreeData()
        this.$eventBus.$emit('doList', {})
      } else if (Number(tab.index) === 1) {
        $('#device-tree').addClass('deviceTree')
        this.loadTagTreeData()
        this.$eventBus.$emit('doList', {})
      }
    },

    handleSaveTag(tagIds, callback) {
      const selectTreeID = this.treeNodeData.id
      this.$store
        .dispatch('device/doSaveTagByID', {
          terminalGroupId: selectTreeID,
          tagIds: tagIds,
        })
        .then((res) => {
          callback && callback()
          this.$message.success('保存成功')
        }).catch(res => {
          this.$message.error(res.msg)
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.deviceTree {
  width: 100%;
  .el-tabs--border-card {
    border: 0 !important;
  }
  ::v-deep .el-tabs--border-card .el-tabs__content {
    padding: 0;
  }
}
.ctl-box {
  width: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  overflow-x: hidden;
}
.shuaxin {
  color: red；;
}
.dtree-wrap {
  // overflow-x: scroll;
  ::v-deep .el-tabs__item {
    padding: 0 !important;
    width: 125px;
    text-align: center;
  }
  ::v-deep .el-tabs__item:last-child {
    border-right: 0 !important;
  }
  // ::v-deep .el-tabs__item.is-active{background: #fff;border-bottom:0 !important;
  //   }
}
.tree-box {
  width: 248px;
  height: calc(100vh - 200px);
  overflow: auto;

  .tree {
    height: 100%;
    ::v-deep .el-tree {
      min-width: 100%;
      display: inline-block !important;
    }
  }

  &.no-ctl {
    height: calc(100vh - 150px);
    .tree {
      height: 100%;
      ::v-deep .el-tree {
        min-width: 100%;
        display: inline-block !important;
      }
    }
  }
}
</style>